import 'package:environmental_les_app/common/utils.dart';
import 'package:environmental_les_app/common/widgets/button_public_rect.dart';
import 'package:environmental_les_app/common/widgets/search_entry_widget.dart';
import 'package:environmental_les_app/common/widgets/top_screen_widget.dart';
import 'package:environmental_les_app/page/mine/knowledge_library/widgets/search_input_view.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'custom_select_widget.dart';

class EnterpriseSelectionWidget extends StatefulWidget {
  final Map<String, dynamic>? initialSelected;
  final Function(Map<String, dynamic>)? onSelectionChanged;
  const EnterpriseSelectionWidget(
      {super.key, this.initialSelected, this.onSelectionChanged});

  @override
  State<EnterpriseSelectionWidget> createState() =>
      _EnterpriseSelectionWidgetState();
}

class _EnterpriseSelectionWidgetState extends State<EnterpriseSelectionWidget> {
  final List<Map<String, String>> _peopleList = [
    {
      'name': '张三',
      'role': '大队长',
      'department': '准格尔旗环境监察大队',
      'location': '(办公室)'
    },
    {
      'name': '李四',
      'role': '中队长',
      'department': '准格尔旗环境监察大队',
      'location': '(办公室)'
    },
    {
      'name': '王五',
      'role': '队员',
      'department': '准格尔旗环境监察大队',
      'location': '(办公室)'
    },
    {
      'name': '赵六',
      'role': '队员',
      'department': '准格尔旗环境监察大队',
      'location': '(办公室)'
    },
    {
      'name': '钱七',
      'role': '队员',
      'department': '准格尔旗环境监察大队 (办公室)',
      'location': '(办公室)'
    },
  ];

  final Map<String, List<String>> _selectedFilters = {};

  // 筛选项
  final List<Map<String, dynamic>> _filterData = [
    {
      "title": "所属行业",
      "prop": "unit",
      "multiSelect": false,
      "filter": [
        {"name": "单位1", "value": "1"},
        {"name": "单位2", "value": "2"},
        {"name": "单位3", "value": "3"},
      ],
    },
  ];

  // 使用Set来存储选中的索引，方便实现多选
  // 设计图看起来是单选，但这种UI通常用于多选，这里以单选为例，初始化第一个为选中
  int? _selectedIndex = 0;

  void _updateSelection(Map<String, dynamic>? result) {
    updateSelectedFilters(_selectedFilters, _filterData, result);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      title: '企业选择',
      body: Column(
        children: [
          // 顶部搜索和筛选区域
          _buildTopBar(),
          vGap10,
          // 人员列表
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 10.0),
              itemCount: _peopleList.length,
              itemBuilder: (context, index) {
                final person = _peopleList[index];
                final isSelected = _selectedIndex == index;
                return buildPersonListItem(person, isSelected, () {
                  setState(() {
                    // 单选逻辑
                    _selectedIndex = index;
                    // 如果要实现多选，可以使用Set并修改这里的逻辑
                  });
                });
              },
            ),
          ),
          // 底部确认按钮
          _buildConfirmButton(),
        ],
      ),
    );
  }

  // 构建顶部搜索和筛选栏
  Widget _buildTopBar() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 10),
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      child: Column(
        children: [
          // 搜索框
          InkWell(
              onTap: () => Get.to(() => const SearchInputView()),
              child: const SearchEntryWidget(hintText: "搜索联系人")),
          // 筛选按钮
          TopScreenWidget(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            filterData: _filterData,
            initialSelected: _selectedFilters,
            onSelectionChanged: (selected) {
              // selected is Map<String, List<String>>?
              if (selected == null) {
                _updateSelection(null);
              } else {
                // controller.updateSelection accepts Map<String, dynamic>? where values may be List
                _updateSelection(selected.map((k, v) => MapEntry(k, v)));
              }
              // reload list after selection change
              setState(() {});
            },
          ),
        ],
      ),
    );
  }

  // 构建底部的确认按钮
  Widget _buildConfirmButton() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.fromLTRB(16, 12, 16, 24), // 底部增加padding以避开系统导航栏
      color: Colors.white,
      child: ButtonPublicRect(
        onPressed: () {
          // 确认按钮的点击逻辑
          if (_selectedIndex != null) {
            final selectedPerson = _peopleList[_selectedIndex!];
            widget.onSelectionChanged?.call(selectedPerson);
            Get.back();
          } else {
            ToastUtil.showToast("请选择一个企业");
          }
        },
        text: '确认',
      ),
    );
  }
}
